import { defineStore } from 'pinia';
import { storage } from '../utils/storage';
import { getRouters } from '../api/auth/menu';
import { navConfig, pathMatchConfig } from '../config/nav';

export const useSidebarStore = defineStore('sidebar', {
    state: () => ({
        // 接口相关状态（临时状态，无需持久化）
        menuData: [], // 后端返回的菜单数据
        menuLoading: false, // 菜单加载中状态
        menuError: null, // 菜单加载错误信息

        // 导航激活状态（核心状态，需持久化）
        activeNav: 0, // 一级导航激活索引
        activeSubNav: navConfig.reduce((acc, item) => {
            acc[item.key] = 0;
            return acc;
        }, {}),
        generationType: 0,
        lastPaths: navConfig.reduce((acc, item) => {
            acc[item.key] = item.secondLevel.defaultPath;
            return acc;
        }, {}),
    }),

    getters: {
        availableNavConfigs() {
            const baseConfigs = this.menuError ? navConfig : navConfig.filter(
                config => this.menuData.some(menu => menu.name === config.title)
            );
            return baseConfigs.map((config, index) => ({ ...config, activeNavIndex: index }));
        },
    },

    actions: {
        async fetchMenuData() {
            this.menuLoading = true;
            this.menuError = null;
            this.menuData = [];

            try {
                const response = await getRouters();
                if (!response || !Array.isArray(response.data)) {
                    throw new Error('接口返回格式错误，data应为数组');
                }

                this.menuData = response.data
                    .map(item => ({
                        name: item.meta?.title || '',
                        icon: item.meta?.icon || '',
                        path: item.path || '',
                    }))
                    .filter(item => item.path && item.name);

                if (this.menuData.length === 0) {
                    throw new Error('未获取到有效菜单');
                }

                this.initializeNavState();
            } catch (err) {
                console.error('菜单加载失败:', err);
                this.menuError = err.message || '菜单加载失败，请重试';
                this.initializeNavState();
            } finally {
                this.menuLoading = false;
            }
        },

        initializeNavState() {
            const defaultConfig = this.getDefaultAvailableConfig();
            this.setActiveNav(defaultConfig.activeNavIndex);
            this.setActiveSubNav(defaultConfig.key, 0, defaultConfig.secondLevel.defaultPath);
            if (defaultConfig.key === 'media') this.setGenerationType(0);
        },

        getDefaultAvailableConfig() {
            const available = this.availableNavConfigs;
            if (available.length === 0) {
                return { ...navConfig[0], activeNavIndex: 0 };
            }
            return available.find(cfg => this.menuData.some(menu => menu.name === cfg.title))
                || available[0];
        },

        getDefaultRoute() {
            const defaultConfig = this.getDefaultAvailableConfig();
            return defaultConfig.secondLevel.defaultPath || '/';
        },

        setActiveNav(index) {
            this.activeNav = index;
            this.persistState();
        },

        setActiveSubNav(key, index, path) {
            this.activeSubNav[key] = index;
            if (path) this.lastPaths[key] = path;
            this.persistState();
        },

        setGenerationType(type) {
            this.generationType = type;
            this.persistState();
        },

        syncStateFromPath(path) {
            const matchedConfig = this.availableNavConfigs.find(cfg =>
                path.startsWith(cfg.pathPrefix)
            );

            if (matchedConfig) {
                this.setActiveNav(matchedConfig.activeNavIndex);
                this.handleSubPathMatch(path, matchedConfig);
            } else {
                const defaultConfig = this.getDefaultAvailableConfig();
                this.setActiveNav(defaultConfig.activeNavIndex);
                this.setActiveSubNav(defaultConfig.key, 0, defaultConfig.secondLevel.defaultPath);
            }
        },

        handleSubPathMatch(path, config) {
            const matchHandler = pathMatchConfig[config.key];
            if (typeof matchHandler === 'function') {
                matchHandler(path, this.setActiveSubNav.bind(this), this.setGenerationType.bind(this), config.secondLevel.defaultPath);
            } else {
                this.setActiveSubNav(config.key, 0, config.secondLevel.defaultPath);
                if (config.key === 'media') this.setGenerationType(0);
            }
        },

        persistState() {
            const persistData = {
                activeNav: this.activeNav,
                activeSubNav: this.activeSubNav,
                generationType: this.generationType,
                lastPaths: this.lastPaths,
            };
            storage.set('sidebarState', persistData);
        },

        restoreState() {
            try {
                const savedState = storage.get('sidebarState');
                if (savedState && typeof savedState === 'object') {
                    this.$patch({
                        activeNav: savedState.activeNav ?? this.activeNav,
                        activeSubNav: savedState.activeSubNav ?? this.activeSubNav,
                        generationType: savedState.generationType ?? this.generationType,
                        lastPaths: savedState.lastPaths ?? this.lastPaths,
                    });
                }
            } catch (err) {
                console.error('状态恢复失败:', err);
                storage.remove('sidebarState');
            } finally {
                this.initializeNavState();
            }
        },
    },
});